/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 pjoc.pub, blademainer.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package pub.pjoc.aop;

import com.google.common.base.Optional;
import pub.pjoc.pay.vo.ReturnResult;
import pub.pjoc.util.BindingResultUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

/**
 * @author xiongyingqi
 * @since 16-12-15 下午9:13
 */
@Aspect
@Component
@Order(0)
public class BindingResultAspect {
  private static final Logger logger = LoggerFactory.getLogger(BindingResultAspect.class);

  @Pointcut("execution(* com.xunlei.channel.api.controller..*.*(..))")
  public void controllerMethods() {
  }

  @Pointcut("execution(public com.xunlei.channel.api.entity.ReturnResult (com.xunlei.channel.api..*)" +
      ".*(.., @javax.validation.Valid (*),org.springframework.validation.BindingResult, ..))")
  public void validMethods() {
  }

  @Around("validMethods()")
  public Object aop(ProceedingJoinPoint pjp) throws Throwable {
    Object[] args = pjp.getArgs();
    for (Object arg : args) {
      Optional<ReturnResult> returnResultOptional = buildResultIfHasErrors(arg);
      if (returnResultOptional.isPresent()) {
        if (logger.isDebugEnabled()) {
          logger.debug("Intercept binding result, and returns: {}", returnResultOptional.get());
        }
        return returnResultOptional.get();
      }
    }
    return pjp.proceed();
  }

  private Optional<ReturnResult> buildResultIfHasErrors(Object arg) {
    if (!(arg instanceof BindingResult)) {
      return Optional.absent();
    }
    BindingResult bindingResult = (BindingResult) arg;
    if (!bindingResult.hasErrors()) {
      return Optional.absent();
    }
    ReturnResult returnResult = BindingResultUtils.buildResult(bindingResult);
    if (returnResult == null) {
      return Optional.absent();
    }
    return Optional.of(returnResult);
  }


}
